/**
 * @desc  所有的字典都来之系统设置
 * */
import * as dictionaryValueApi from "@/api/manage/dictionaryValue.js";
import  cookie from "js-cookie";
import  * as mesTagLibraryApi from '@/api/mesTagLibrary.api.js'




function safeParse(str) {
  try {
    return JSON.parse(str);
  } catch (e) {
    console.error(e)
    return null
  }

}

export const ajaxDicList = function (code,iscache=true) {
  if (!code) {
    return null;
  }
  if(iscache/*默认使用缓存*/){
    var uuidKey = `dic.${code}`;
    var codeInCookie = cookie.get(uuidKey);
    if (codeInCookie && sessionStorage.getItem(uuidKey)) {
      return Promise.resolve(safeParse(sessionStorage.getItem(uuidKey)))
    }
  }
  return dictionaryValueApi.getvaluelistbydiscode(code).then(res => res.data).then(datalist => {


//不缓存
    if (!datalist) {
      return Promise.resolve([])
    }


//不缓存
    if (datalist && datalist.length <= 0) {
      return Promise.resolve([])
    }



    datalist = datalist.map(item => {
      return {
        dicId: item?.id,
        label: item.name,
        value: item.code + "",
        state :item.state,
        remarks :item.remarks,
        disabled:item?.state==5
      }
    })

    /*dic code  存储 半个小时*/
    cookie.set(uuidKey, 1, {expires: .5 / 24})
    sessionStorage.setItem(uuidKey, JSON.stringify(datalist))
    return Promise.resolve(datalist)
  })
}

//获取 标签列表
export const ajaxLabaryList = function (params) {
  if (!(params&&params.groupId)) {
    return null;
  }
  return mesTagLibraryApi.getList(params).then(res => res.data).then(datalist => {


//不缓存
    if (!datalist) {
      return Promise.resolve([])
    }


//不缓存
    if (datalist && datalist.length <= 0) {
      return Promise.resolve([])
    }




    datalist = datalist.map(item => {
      return {
        label: item.name,
        value: item.id + "",
        state :item.state
      }
    })

    /*dic code  存储 半个小时*/
    return Promise.resolve(datalist)
  })
}


export function ToFixed (value, params) {
  if (!value) return '';
  if(typeof value=='string') return value;
  if (!params) {
    params = 2;
  }
  return value.toFixed(params);
}



